<?php

namespace app\shop\controller;

use think\Controller;

class Settlement extends Controller
{
    //构造函数
    public function __construct()
    {
        parent::__construct();
        //加载模型
        $this->userModel = model('common/User/User');
        $this->bannerModel = model('common/User/Banner');
        $this->shopModel = model('common/User/Shop');
        $this->cartModel = model('common/User/Cart');
        $this->addressModel = model('common/User/Address');
        $this->regionModel = model('common/User/Region');
        $this->couponModel = model('common/User/Coupon');
        $this->couponReceiveModel = model('common/User/CouponReceive');
        $this->orderModel = model('common/User/Order');
        $this->orderProductModel = model('common/User/OrderProduct');
        $this->businessRecordModel = model('common/User/BusinessRecord');
    }


    // 提交订单后获取提交的商品信息
    public function getSettleList(){
      if($this->request->isPost()){
        $mobile = $this->request->param('mobile');
        $uid = $this->request->param('uid');
        $ids = $this->request->param('ids');
        $price = (float)$this->request->param('price');
        $isStatic = $this->request->param('isStatic');   
        $totalprice = $price/100;
        // halt($isStatic);
        $idsArray = json_decode($ids, true);
        // halt()
        $uData = [
          'id'=>$uid,
          'mobile'=>$mobile
        ];
        $isUserRes = $this->userModel->where($uData)->select();
        if($isUserRes){
          // 如果isStatic==2，就是购物车的支付，否则就是在详情页立即购买的支付
          if($isStatic==2){
            $settleList = $this->cartModel->all($idsArray);
            // $pid = $this->cartModel->all($idsArray);
            $arr=[];
            foreach($settleList as $item){
              $arr[]=$item['pid'];
            }
            // 连表查询！！！！！！！！！！！！
            $where=[
              'uid'=>$uid,
              'pid'=>['IN',$arr]
            ];
            $settleList = $this->cartModel->with('product')->where($where)->select();
            $prdList = $this->shopModel->whereIn('id',$arr)->select();
          }else{
            $totalprice = ($price*100)/100;
            $id = (int)json_decode($ids);
            $prdList  = $this->shopModel->where('id',$id)->select();
            $settleList = [];
          }


          $isdefRes =  $this->addressModel->where('uid',$uid)->where('isDefault',1)->find();
          if ($isdefRes) {
            $addressdata = $isdefRes;
          }else{
            $addressdata = $this->addressModel->where('uid',$uid)->find();
          }
          // halt($addressdata);
          

          // $settleData['totalPrice'] = $totalprice;
          $settleData=[
            'settleList'=>$settleList,
            'totalPrice'=>$totalprice,
            'addressData'=>$addressdata,
            'prdList'=>$prdList,
          ];

          // halt($settleData);

          $this->success('查询提交商品列表成功',null,$settleData);
          exit;
        }else{
          $this->error('用户非法',null);
          exit;
        }

    }

  } 

  public function updateType(){
    if($this->request->isPost()){
      $mobile = $this->request->param('mobile');
      $uid = $this->request->param('uid');
      $ids= json_decode($this->request->param('ids'));

      // halt($ids);

      $uData = [
        'id'=>$uid,
        'mobile'=>$mobile
      ];
      $isUserRes = $this->userModel->where($uData)->select();
      if($isUserRes){
        $update = [
          'type'=>-1
        ];
        $where=[
          'id'=>['IN',$ids]
        ];
        // halt(11111);
        $updateRes = $this->couponReceiveModel->where($where)->update($update);
        $this->success('更新成功',null);
      }

    }
  }

  //确认支付功能--要操作事务
  public function confirmBuy(){
    if($this->request->isPost()){
      $ajaxData = $this->request->param();
      $status = $this->request->param('status');
      
      // halt($ajaxData);
      /**
       * 有优惠券的情况下：
       * 第一次修改用户的余额  （用户更改余额）
       * 增加订单              （增加订单）
       * 增加订单商品表         （增加订单商品）
       * 增加用户消费表          （增加用户消费）
       * 修改商品表             （修改商品库存）
       * 修改购物车表           （修改购物车表）
       * 修改优惠券领取表        （改变用户优惠券状态）
       */
      // 存放要增加订单的数据
      $isUser = [
        'id'=>$ajaxData['uid'],
        'mobile'=>$ajaxData['mobile']
      ];
      $isUserRes = $this->userModel->where($isUser)->select();
      // halt($isUserRes);
      if($isUserRes){
        //  开启事务
        $this->userModel->startTrans();
        $this->orderModel->startTrans();
        $this->orderProductModel->startTrans();
        $this->businessRecordModel->startTrans();
        $this->shopModel->startTrans();
        $this->cartModel->startTrans();
        $this->couponReceiveModel->startTrans();   
        // 查询用户的money
        $getMoney = $this->userModel->where($isUser)->value('money');
        // halt($ajaxData['totalPrice']);
        // 支付状态（$status）：0、全部1、已支付2、已发货3、已收货-1、退货-2、未支付
        // 用户余额大于提交商品的总价，并且用户是已支付状态，则可对用户余额进行更改
        if($getMoney>=$ajaxData['totalPrice'] && $status == 1){
          $newMoney =  $getMoney-$ajaxData['totalPrice'];
          // halt($newMoney);
          $updateData = ['money'=>$newMoney];
          // 1.修改用户的余额
          $updataMoney = $this->userModel->where($isUser)->update($updateData);
          if($updataMoney===FALSE){
            // $this->userModel->rollback();
            $this->error('更新余额失败',null);
            exit;
          }
        }
        // 未支付状态
        elseif($getMoney>=$ajaxData['totalPrice'] && $status == -2){
          // $this->success('订单未支付');
          $updateData = ['money'=>$getMoney];
          $updataMoney = $this->userModel->where($isUser)->update($updateData);
        }
        // 余额不足
        else{
          $this->error('余额不足,剩余:'.$getMoney.'元',null);
          exit;
        }

        // 2.增加订单操作
        // 存放要增加订单的数据
        $orderData = [
          // 前缀时ORD-的订单号，  build_code()这个方法在common.php里，是公共函数，用来生成订单号
          'code'=> build_code('ORD-'),
          'busid'=>$ajaxData['uid'],
          'businessaddrid'=>$ajaxData['businessaddrid'],
          'remark'=>$ajaxData['remark'],
          'amount'=>$ajaxData['totalPrice'],
          'cid'=>$ajaxData['couponId'],
          'status'=>(int)$status,
          'createtime'=>time(),
        ];

        // halt($orderData);

        $orderRes = $this->orderModel->save($orderData);

        // halt($orderRes);
        if($orderRes === FALSE){
            $this->userModel->rollback();
          $this->error('增加订单失败',null);
          exit;
        }

        // 3.增加订单商品表
        $ordPrdData = [
          'proid'=>json_decode($ajaxData['pids']),
        ];
        // halt($ordPrdData);
        $pids = json_decode($ajaxData['pids']);
        $pids = array_map('intval', $pids);
        // halt($pids);
        // halt($this->cartModel->whereIn('pid',$pids)->select());
        $where = [
          'uid'=>$ajaxData['uid'],
          'pid'=>['IN',$pids]
        ];
        // halt($ajaxData['isStatic']);
        // 1为立即购买 
        if($ajaxData['isStatic']==1){
          // halt($pids);
          $prdRes = $this->shopModel->whereIn('id',$pids)->select();
          // halt($prdRes);
          if($prdRes===FALSE){
            $this->error('查询商品失败',null);
            exit;
          }
          // halt($prdRes);
          foreach($prdRes as $item){
            // halt($item['price']);
            $price = $item['price'];
            // halt($price);
          }
          // halt($price);
          $count = count($pids);
          // halt($count);
          $result = [];
          for ($i = 0; $i < $count; $i++) {
              $result[] = [
                  "proid" => $pids[0],
                  // 这里是立即购买，若加了步进器，可改变量，（暂时为1）
                  "pronum" => 1,
                  "price" => $price,
                  'total' => $price,
                  'orderid' => $this->orderModel->id,
              ];
          }
          $shopRes = $this->shopModel->whereIn('id',$pids)->select();
          if($shopRes===FALSE){
            $this->error('查询商品失败',null);
            exit;
          }
          // halt(111);
        }
        // 2为购物车
        if($ajaxData['isStatic']==2){
          $cartRes = $this->cartModel->where($where)->select();
          if($cartRes===FALSE){
            $this->error('查询购物车失败',null);
            exit;
          }
          $nums = [];
          foreach ($cartRes as $item) {
            $nums[]= $item['num'];
            // $nums[]= $item['num'];
          }
          $ordPrdData['pronum']=$nums;
          // halt($cartRes);
          // halt($pids);
          // 查价格
          $prices = [];
          foreach($pids as $item){
            $prices[] = $this->shopModel->where('id',$item)->value('price');
          }
          $shopRes = $this->shopModel->whereIn('id',$pids)->select();
          $ordPrdData['price']=$prices;
          if($shopRes===FALSE){
            $this->error('查询商品失败',null);
            exit;
          }
          /**
           * 这里是处理成能够批量新增的格式：
           * // 批量新增
           *$list = [
          *    ['name'=>'thinkphp','email'=>'thinkphp@qq.com'],
          *    ['name'=>'onethink','email'=>'onethink@qq.com']
          *];
          *
          */
          $result = [];
          $count = count($ordPrdData["proid"]);
          // halt($this->orderProductModel->id);
          for ($i = 0; $i < $count; $i++) {
              $result[] = [
                  "proid" => $ordPrdData["proid"][$i],
                  "pronum" => $ordPrdData["pronum"][$i],
                  "price" => $ordPrdData["price"][$i],
                  'total' => $ordPrdData["pronum"][$i]*$ordPrdData["price"][$i],
                  'orderid'=> $this->orderModel->id
              ];
          }
        }
        
        // $result = json_decode($result);
        // halt($result);
        // 增加订单商品表操作
        $oderProRes = $this->orderProductModel->saveAll($result);
        // halt($oderProRes);
        if ($oderProRes === FALSE) {
          $this->orderModel->rollback();
          $this->userModel->rollback();
          $this->error('增加订单商品表失败',null);
          exit;
        }

        // 4.增加用户消费记录表
        $recordData = [
          'total'=>$ajaxData['totalPrice'],
          'createtime'=>$ajaxData['createtime'],
          'busid'=>$ajaxData['uid']
        ];
        $uRecordRes = $this->businessRecordModel->save($recordData);
        if($uRecordRes===FALSE){
          $this->orderProductModel->rollback();
          $this->orderModel->rollback();
          $this->userModel->rollback();
          $this->error('增加用户消费记录表失败',null);
          exit;
        }

        // 修改商品库存
        // 先查出对应id的商品
        $shStockRes = $this->shopModel->whereIn('id',$pids)->select();
        // halt($shopRes);
        $stocks = [];
        $buypid  = [];
        // 遍历每一个价格
        foreach ($shopRes as $item) {
          $stocks[]= $item['stock'];
          $buypid[] = $item['id'];
          // $nums[]= $item['num'];
        }
        // halt($stocks);
        $stockCount = count($stocks);
        // halt($stockCount);
        // 查询商品-然后再查库存
        // 购物车时
        if($ajaxData['isStatic']==2){
          $buynumsRes = $this->cartModel->where($where)->select();
          // halt($buynumsRes);
          if($buynumsRes===FALSE){
            $this->error('查询商品失败',null);
            exit;
          }
          $bynums = [];
          foreach($buynumsRes as $item){
            $bynums[] = $item['num'];
          }
          $stockResult = [];
          for ($i = 0; $i < $stockCount; $i++) {
              $id = $buypid[$i];
              $sto = $stocks[$i]-$bynums[$i];
              $stockResult[] = [
                'id'=> $id,
                'stock' => $sto,
              ];
          }
        }
        // 立即购买时
        if($ajaxData['isStatic']==1){
          $stockResult = [];
          for ($i = 0; $i < $stockCount; $i++) {
              $id = $buypid[$i];
              $sto = $stocks[$i]-1;
              $stockResult[] = [
                'id'=> $id,
                'stock' => $sto,
              ];
          }
        }
        
        // 更新商品库存操作
        $updateStockRes = $this->shopModel->isUpdate(true)->saveAll($stockResult);
        if($updateStockRes===FALSE){
          $this->businessRecordModel->rollback();
          $this->orderProductModel->rollback();
          $this->orderModel->rollback();
          $this->userModel->rollback();
          $this->error('更新库存失败',null);
          exit;
        }

        // 修改购物车表
        if($ajaxData['isStatic']==2){
          $delCartRes = $this->cartModel->where($where)->delete();
          if($delCartRes===FALSE){
            $this->shopModel->rollback();
            $this->businessRecordModel->rollback();
            $this->orderProductModel->rollback();
            $this->orderModel->rollback();
            $this->userModel->rollback();
            $this->error('修改购物车失败',null);
            exit;
          }
        }
        

        // 修改优惠券表
        $upType = [
          'type'=>1
        ];
        // halt($ajaxData['couponId']);
        $updateCouponRes = $this->couponReceiveModel->where('cid',$ajaxData['couponId'])->update($upType);
        // halt($updateCouponRes);
        if($updateCouponRes === FALSE){
          $this->cartModel->rollback();
          $this->shopModel->rollback();
          $this->businessRecordModel->rollback();
          $this->orderProductModel->rollback();
          $this->orderModel->rollback();
          $this->userModel->rollback();
          $this->error('修改优惠券失败',null);
          exit;
        }

        if($orderRes === FALSE || $oderProRes === FALSE ||
        $uRecordRes===FALSE || $updateStockRes===FALSE ){
          $this->cartModel->rollback();
          $this->shopModel->rollback();
          $this->businessRecordModel->rollback();
          $this->orderProductModel->rollback();
          $this->orderModel->rollback();
          $this->userModel->rollback();
          $this->error('购买失败',null);
          exit;
        }else{
          $this->userModel->commit();
          $this->orderModel->commit();
          $this->orderProductModel->commit();
          $this->businessRecordModel->commit();
          $this->shopModel->commit();
          $this->cartModel->commit();
          $this->couponReceiveModel->commit();
          if($status == 1){
            $this->success('购买成功', null);
            exit;
          }else{
            $this->success('已取消支付，可到订单进行支付', null);
            exit;
          }
        }
      }
    }
  }




}

?>

